/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import i18n from 'i18next';

import { pickedFaceData, pickedLineData } from '@amcax/base';
import { getIdOfPickedObj } from '@app-base/common/utils/render';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { ctx2 } from '@app-cad/module';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useMemo, useState } from 'react';

type pickedTargetData = pickedLineData | pickedFaceData;

type FormData = {
  profile1?: pickedTargetData;
  profile2?: pickedTargetData;
  keepAllSolution: boolean;
};

type Params = {
  profile1: string;
  profile2: string;
  solution: number;
};

// 相交 - v2 版本（替换 线线相交、面面相交、线面相交）
function CommandCross2({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    profile1: null,
    profile2: null,
    keepAllSolution: true,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { profile1, profile2, solution } = params;

    await initEditDependency([profile1, profile2]);

    setFormData({
      profile1: picker.generatePickObjByPickID(profile1) as pickedTargetData,
      profile2: picker.generatePickObjByPickID(profile2) as pickedTargetData,
      keepAllSolution: solution === -1,
    });

    setSolution(solution);
  }, []);

  const isFormDataValid = (showTip = false) => {
    const { profile1, profile2 } = formData;

    if (profile1 == null || profile2 == null) {
      return false;
    }

    if (getIdOfPickedObj(profile1) === getIdOfPickedObj(profile2)) {
      if ((profile1 as pickedLineData)?.edgeId) {
        if (showTip) MessageTip.warning(`不允许选择相同曲线`);
        return false;
      }
      if ((profile1 as pickedFaceData)?.meshId) {
        if (showTip) MessageTip.warning(`不允许选择相同曲面`);
        return false;
      }
    }

    return true;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid(true)) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-part-intersection', {
      commandName: 'CreateIntersect',
      editDxid: props?.shape || props?.dxid, // 这里shape 是为空
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { profile1, profile2, keepAllSolution } = formData;

    return confirmCommand(
      {
        a: {
          profile1: getIdOfPickedObj(profile1),
          profile2: getIdOfPickedObj(profile2),
          solution: keepAllSolution ? -1 : solution,
        } as Params,
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid(true)) {
      clear();

      setSolution(0);
      setSolutionNum(0);
      return;
    }

    const { nsolution } = await execute(true);

    setSolutionNum(nsolution);

    ctx2.viewer.requestRender();
  };

  useEffect(() => {
    preview();
  }, [formData]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      profile1: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurveSurface,
      },
      profile2: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurveSurface,
      },
      ...(solutionNum > 1
        ? {
            keepAllSolution: {
              type: 'boolean',
              title: '保留所有解',
            },
          }
        : {}),
      ...(formData?.keepAllSolution == false && solutionNum > 1
        ? { solution: MULTI_SOLUTION_SCHEMA }
        : {}),
    },
  };

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  useAsyncEffect(preview, [solution]);

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      submitLoading={isLoading}
      schema={schema}
      formData={finalFormData}
      onChange={(v) => {
        let solution = v.solution[0];
        if (v.keepAllSolution === false && solution === -1) {
          solution = 0;
        }
        if (
          v.profile1 !== formData.profile1 ||
          v.profile2 !== formData.profile2
        ) {
          // 如果曲线或曲面发生变化，重置 solution
          solution = 0;
        }

        setFormData(v);
        setSolution(solution);
      }}
      extraUiSchema={{
        profile1: {
          'ui:placeholder': '请输入曲线或曲面',
          'ui:autofocus': props == null,
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        profile2: {
          'ui:placeholder': '请输入曲线或曲面',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
        keepAllSolution: {
          'ui:widget': 'checkbox',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      noValidate
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdCross2: CurvedBaseCommand = {
  id: 'CmdCross2',
  label: 'command.cross',
  icon: 'commands/curved/vertex-plane-int',
  help: {
    remark: 'tips.redo',
  },
  create: (label, onClose, props) => (
    <CommandCross2
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
